from django.db import models
from django.core.validators import RegexValidator, MinValueValidator
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import (
    AbstractUser,
    Group,
    Permission  # 添加显式导入
)

class CustomUser(AbstractUser):
    groups = models.ManyToManyField(
        Group,
        verbose_name='groups',
        blank=True,
        related_name="customuser_groups",
        related_query_name="customuser",
    )
    
    user_permissions = models.ManyToManyField(
        Permission,  # 使用显式导入的Permission
        verbose_name='user permissions',
        blank=True,
        related_name="customuser_permissions",
        related_query_name="customuser",
    )

    class Meta:
        db_table = 'custom_user' 

class ZbirdAccount(models.Model):
    id = models.AutoField(primary_key=True)
    tag = models.CharField('标签（就是紫鸟上的中文标签，如JNA-0005丁帅-吴敏）',max_length=255,null=True, blank=True)
    epname = models.CharField('企业名称', max_length=255)
    loginname = models.CharField('登录账号', max_length=100)
    username = models.CharField('用户名',max_length=255)
    password = models.CharField('密码',max_length=255)
    create_date = models.DateTimeField('创建时间',auto_now_add=True)
    update_date = models.DateTimeField('更新时间',auto_now=True)
    is_active = models.BooleanField('是否启用',default=True)
    last_login=models.DateTimeField('最后登录时间',null=True, blank=True)
    def __str__(self):
        return self.epname

    class Meta:
        verbose_name = '账号管理'
        verbose_name_plural = '账号管理'

class WalmartAccount(models.Model):
    id = models.AutoField(primary_key=True)
    orderindex = models.IntegerField('排序序号', default=0)
    username = models.CharField('用户名', max_length=255)
    loginname = models.CharField('登录账号', max_length=100)
    tag = models.CharField('标签名称',max_length=255)
    password = models.CharField('密码（不录）',max_length=255)
    zbird_account = models.ForeignKey(ZbirdAccount, on_delete=models.CASCADE, verbose_name='关联账号')
    create_date = models.DateTimeField('创建时间',auto_now_add=True)
    update_date = models.DateTimeField('更新时间',auto_now=True)
    def __str__(self):
        return f"{self.loginname}"

    class Meta:
        verbose_name = '沃尔玛账号'
        verbose_name_plural = '沃尔玛账号管理'

class Keyword(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField('用户名', max_length=255)
    keyword = models.CharField('关键词', max_length=255)
    is_prohibited = models.BooleanField('是否禁用', default=False)
    create_date = models.DateTimeField('创建时间',auto_now_add=True)
    update_date = models.DateTimeField('更新时间',auto_now=True)
    lastdownloadtime=models.DateTimeField('最近下载时间',blank=True,auto_now=True)
    class Meta:
        verbose_name = '关键词管理'
        verbose_name_plural = '关键词管理'

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    productid = models.CharField('产品ID', max_length=50)
    walmart_account = models.ForeignKey(WalmartAccount, on_delete=models.CASCADE)
    username = models.CharField('用户名', max_length=255)
    product_name = models.TextField('产品名称')
    is_following = models.BooleanField('是否跟卖',default=False)
    follow_price_strategy = models.CharField('关注价格策略',max_length=255, choices=[('lower_by_0.1', 'Lower by 0.1'), ('fixed_time', 'Fixed Time')])
    follow_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    keywords = models.CharField('关键词', max_length=255)
    create_date = models.DateTimeField('创建时间',auto_now_add=True)
    update_date = models.DateTimeField('更新时间',auto_now=True)
    link = models.CharField('产品链接', max_length=255, null=True, blank=True)
    # New fields for Walmart Canada platform product information
    category = models.CharField('产品分类', max_length=100)

    price = models.DecimalField('价格', max_digits=10, decimal_places=2)
    stock = models.IntegerField('库存')
    description = models.TextField('描述',blank=True, null=True)
    image = models.URLField('图片',max_length=500, blank=True, null=True)  # URL to the product image
    brand = models.CharField('品牌',max_length=255, blank=True, null=True)  # Brand of the product
    product_name = models.CharField('产品名称', max_length=255)

    current_cart_seller = models.CharField('当前购物车卖家',max_length=255, blank=True, null=True)  # Current seller in the cart
    own_follow_price = models.DecimalField('跟卖价格',max_digits=10, decimal_places=2, null=True, blank=True)  # Your own follow price
    upc = models.CharField('UPC编码', max_length=50)
    newprice = models.DecimalField('跟卖价格',max_digits=10, decimal_places=2, null=True, blank=True)  # New price of the product
    newsku = models.CharField('新sku', max_length=255, blank=True, null=True)  # New SKU field
    taxcode=models.CharField('税码',max_length=255, blank=True, null=True)  # Tax code of the product
    sku = models.CharField(max_length=255, blank=True, null=True)  # Ensure this field exists
    # Add more fields as needed for additional product information
    rating = models.FloatField('评分',null=True, blank=True)
    reviews = models.IntegerField('评价数量',null=True, blank=True)
    hasexcept = models.CharField('是否有异常',max_length=255, blank=True, null=True)

    # def fetch_upc(self):
    #     """自动获取UPC"""
    #     from .interface.WalmartScraper import get_walmart_upc
    #     self.upc = get_walmart_upc(self.link)
    #     self.save()

    class Meta:
        verbose_name = '产品信息'
        verbose_name_plural = '下载产品信息管理'

class SkuKeywordsHistory(models.Model):
    id = models.AutoField(primary_key=True)

    sku = models.CharField('SKU编号', max_length=50)
    keywords = models.TextField('历史关键词')
    opdate = models.DateTimeField('操作时间', auto_now_add=True)
    fromprice = models.FloatField('从价格',null=True, blank=True)
    toprice = models.FloatField('改到价格',null=True, blank=True)
    username = models.CharField('用户名',max_length=20, null=True, blank=True)

    class Meta:
        verbose_name = 'SKU关键词历史'
        verbose_name_plural = 'SKU关键词历史记录'
        db_table = 'sku_keywords_history'
        managed = False  # This tells Django not to manage the table's lifecycle

    def __str__(self):
        return f"{self.sku} - {self.keywords}" 

class skus(models.Model):
    id = models.AutoField(primary_key=True)
    sku = models.CharField('SKU编号', max_length=50)
    walmart_account = models.ForeignKey(WalmartAccount, on_delete=models.CASCADE, verbose_name='沃尔玛账号')
    username = models.CharField('用户名', max_length=255, null=True, blank=True)
    current_cart_seller = models.CharField('当前购物车卖家',max_length=255, blank=True, null=True)  # Current seller in the cart
    own_follow_price = models.DecimalField('跟卖价格',max_digits=10, decimal_places=2, null=True, blank=True)  # Your own follow price
    upc = models.CharField(
        'UPC编码',
        max_length=20,  # 限制长度为标准UPC长度
        validators=[
            RegexValidator(
                regex='^[0-9]{12,14}$',
                message='UPC必须为12-14位纯数字'
            )
        ],
        help_text="请输入12-14位标准UPC编码",  # 添加帮助提示
        db_index=True,  # 添加数据库索引提升查询性能
        editable=True  # 确保该字段可编辑
    )
    currency = models.CharField('货币',max_length=255, blank=True, null=True)
    newprice = models.DecimalField('跟卖价格',max_digits=10, decimal_places=2, null=True, blank=True)  # New price of the product
    price2 = models.DecimalField('旧价格',max_digits=10, decimal_places=2, null=True, blank=True)
    newsku = models.CharField('新sku', max_length=255, blank=True, null=True)  # New SKU field
    taxcode=models.CharField('税码',max_length=255, blank=True, null=True)  # Tax code of the product
    # Add more fields as needed for additional product information
    product_name = models.CharField('产品名称', max_length=255)
    category = models.CharField('分类',max_length=255)
    image = models.URLField('图片',max_length=500, blank=True, null=True)  # URL to the 
    lastfollow_date= models.DateTimeField('最新跟卖时间',blank=True,auto_now=True)
    lastchangeprice_date= models.DateTimeField('最新改价时间',blank=True,auto_now=True)
    link = models.CharField('产品链接', max_length=255, null=True, blank=True)
    rating = models.FloatField('评分',null=True, blank=True)
    reviews = models.IntegerField('评价数量',null=True, blank=True)
    hasexcept = models.CharField('是否有异常',max_length=255, blank=True, null=True)
    is_following = models.BooleanField('是否跟卖',default=False)
    create_date = models.DateTimeField('创建时间',auto_now_add=True)
    update_date = models.DateTimeField('更新时间',auto_now=True)
    price = models.DecimalField(
        '价格',
        max_digits=10,
        decimal_places=2,
        validators=[
            MinValueValidator(0.01, '价格必须大于0')
        ]
    )
    is_following_choices = (
        (1, '正在跟卖'),
        (0, '未跟卖')
    )
    is_following = models.IntegerField('跟卖状态', choices=is_following_choices, default=0)
    class Meta:
        app_label = 'app'  # 必须与INSTALLED_APPS中的应用名称一致
        verbose_name = 'SKU管理'
        verbose_name_plural = 'SKU管理'
        db_table = 'app_skus_new'
        managed = True  # 改为 True 让 Django 管理表结构